import {
  CallHandler,
  ExecutionContext,
  HttpStatus,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { renderCommonResult } from './CommonPageDto';

/**
 * 状态拦截器，封装到这里，统一返回格式
 */
export class ResultInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((data) => {
        const http = context.switchToHttp();
        const res = http.getResponse();
        res.status(HttpStatus.OK);
        return renderCommonResult(data);
      }),
    );
  }
}
